//
//  FeedbackViewModel.swift
//  LeTu
//
//  Created by gy on 2023/12/27.
//

import Foundation
import class HXPHPicker.PhotoAsset

class FeedbackVM {
    
    // 头像
    var picData: Data?
    // 临时url
    private var tempHeadUrls = [String]()
    
    var hasPicture = BehaviorSubject(value: false)
    var selectPictures = [UIImage]() {
        didSet {
            self.hasPicture.onNext(selectPictures.count > 0)
        }
    }
    var selectPictureAssets = [PhotoAsset]()
    
    // MARK: -  提交意见反馈
    func commitFeedback(content: String, completeHandle: @escaping NetworkRequestHandle) {
    
        
        tempHeadUrls = []
        let picDatas = selectPictures.compactMap { $0.compressImage(image: $0, maxLength: 1024*1024) }
        let queue = DispatchQueue(label: "CommitFeedbackQueue", attributes: .concurrent)
        let sema = DispatchSemaphore(value: 1)
        
        // 上传文件
        queue.async { [weak self] in

            sema.wait()

            guard picDatas.count > 0 else {
                sema.signal()
                return
            }
            
            FeedbackVM.uploadMulPicture(datas: picDatas) { [weak self] dialog in
                guard let strongSelf = self, let urls = dialog.data as? [String], urls.count > 0 else {
                    sema.signal()
                    return
                }
                strongSelf.tempHeadUrls = urls
                sema.signal()
            }

           
        }
        
        // 提交反馈
        queue.async { [weak self] in
            
            sema.wait()
            
            var params = ["content": content]
            if let strongSelf = self, strongSelf.tempHeadUrls.count > 0 {
                for index in 0 ..< strongSelf.tempHeadUrls.count {
                    params["picUrl\(index+1)"] = strongSelf.tempHeadUrls[index]
                }
            }
            
            MYLog("提交反馈参数", params)
            apiProvider.request(api: .commitFeedback(params: params)) { json, jsonArr, code in
                            
                MYLog("提交反馈：\(json)")
                var dialog = DialogMessage()
                guard code == 200, let respone = Mapper<ResponseModel>().map(JSON: json) else {
                    sema.signal()
                    completeHandle(dialog)
                    return
                }
                dialog.code = respone.code
                dialog.message = respone.msg

                sema.signal()
                completeHandle(dialog)
                
            } failureHandler: { error in
                sema.signal()
                completeHandle(DialogMessage())
            }
        }
        
    }
    
    // MARK: - 上传文件
    static func updateFile(_ data: Data, completeHandle: @escaping NetworkRequestHandle) {
        
        apiProvider.request(api: .updateFile(data: data)) { json, jsonArr, code in
            
            MYLog("上传文件：", json)
            var dialog = DialogMessage()
            guard code == 200, let pm = Mapper<ResponseModel>().map(JSON: json), let urlDic = pm.data as? [String: Any], let url = urlDic["url"] as? String else { return completeHandle(dialog) }
            dialog.code = pm.code
            dialog.message = pm.msg
            dialog.data = url
            completeHandle(dialog)
            
        } failureHandler: { error in
            completeHandle(DialogMessage())
        }
        
    }
    
    // MARK: - 多处上传
    static private func uploadMulPicture(datas: [Data], completeHandle: @escaping NetworkRequestHandle) {
        
        let queue = DispatchQueue(label: "CommitFeedbackMulImage")
        let group = DispatchGroup()
        
        var urls = [String]()
        
        for data in datas {
            
            group.enter()
            queue.async {
                                
                FeedbackVM.updateFile(data) { dialog in
                    
                    if dialog.code == 200, let url = dialog.data as? String {
                        urls.append(url)
                    }
                    
                    group.leave()
                }
                
            }
            
        }
        
        group.notify(queue: queue) {
            var dialog = DialogMessage()
            dialog.data = urls
            completeHandle(dialog)
        }
        
    }
    
}
